package com.lvhaosb.newpneumonia.tools;

import java.lang.reflect.Field;

/**
 * 实体类 工具
 */
public class ClassTool {

    /**
     * 实例相同字段赋值,赋值条件：属性名相同，类型相同
     * object1 的属性赋值到 object2
     *
     * @param object1
     * @param object2
     * @throws ClassNotFoundException
     * @throws IllegalAccessException
     */
    public void classAssignment(Object object1, Object object2) throws ClassNotFoundException, IllegalAccessException {
        //Class clazz1 = Class.forName(object1.getClass().getName());
        //Class clazz2 = Class.forName(object2.getClass().getName());
        Class clazz1 = object1.getClass();
        Class clazz2 = object2.getClass();

        Field[] fields1 = clazz1.getDeclaredFields();
        Field[] fields2 = clazz2.getDeclaredFields();

        for(Field field1 : fields1){
            // 跳过serialVersionUID
            if(field1.getName().equals("serialVersionUID")){
                continue;
            }
            for(Field field2 : fields2){
                if(field2.getName().equals("serialVersionUID")){
                    continue;
                }
                // 如果属性名相同且类型相同，则赋值
                if (field1.getName().equals(field2.getName()) && field1.getType().toString().equals(field2.getType().toString()) ) {
                    field1.setAccessible(true);
                    field2.setAccessible(true);
                    field2.set(object2, field1.get(object1));
                }
            }
        }
    }
}
